/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.icee.myth.manager.pipelineFactory;

import com.icee.myth.manager.channelHandler.HttpServerHandlerToWeb;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.handler.codec.http.HttpChunkAggregator;
import org.jboss.netty.handler.codec.http.HttpRequestDecoder;
import org.jboss.netty.handler.codec.http.HttpResponseEncoder;
import org.jboss.netty.handler.execution.ExecutionHandler;
import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor;
import org.jboss.netty.handler.stream.ChunkedWriteHandler;

import static org.jboss.netty.channel.Channels.pipeline;

/**
 *
 * @author yangyi
 */
public class HttpServerToWebPipelineFactory implements ChannelPipelineFactory{

    /***
     * 将OrderedMemoryAwareThreadPoolExecutor变量设置为static类型，保证在不同的pipeline之间是共享的。
     */
    final private static OrderedMemoryAwareThreadPoolExecutor omatpe = new OrderedMemoryAwareThreadPoolExecutor(10, 1048567, 1048567);
    final private static ExecutionHandler executionHandler = new ExecutionHandler(omatpe);

    @Override
    public ChannelPipeline getPipeline() throws Exception {
        // Create a default pipeline implementation.
        ChannelPipeline pipeline = pipeline();

        // Uncomment the following line if you want HTTPS
        //SSLEngine engine = SecureChatSslContextFactory.getServerContext().createSSLEngine();
        //engine.setUseClientMode(false);
        //pipeline.addLast("ssl", new SslHandler(engine));

        pipeline.addLast("decoder", new HttpRequestDecoder());
        // Uncomment the following line if you don't want to handle HttpChunks.
        pipeline.addLast("aggregator", new HttpChunkAggregator(1048576));
        pipeline.addLast("encoder", new HttpResponseEncoder());
        // Remove the following line if you don't want automatic content compression.
        //pipeline.addLast("deflater", new HttpContentCompressor());
        pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());

        /* 把共享的ExecutionHandler实例放在业务逻辑handler之前即可，
        注意ExecutionHandler一定要在不同的pipeline之间共享。
        它的作用是自动从ExecutionHandler自己管理的一个线程池中拿出一个线程来处理排在它后面的业务逻辑handler。
        而worker线程在经过ExecutionHandler后就结束了，它会被ChannelFactory的worker线程池所回收。
        netty额外给我们提供了两种线程池：MemoryAwareThreadPoolExecutor和OrderedMemoryAwareThreadPoolExecutor
        MemoryAwareThreadPoolExecutor确保jvm不会因为过多的线程而导致内存溢出错误，
        OrderedMemoryAwareThreadPoolExecutor是前一个线程池的子类，
        除了保证没有内存溢出之外，还可以保证channel event的处理次序。**/
        pipeline.addLast("executor", executionHandler);
        pipeline.addLast("handler", new HttpServerHandlerToWeb());
        return pipeline;
    }

}
